package com.jms.tomcat.filter;

import javax.servlet.*;
import javax.servlet.ServletException;
import java.io.IOException;

/**
 * 过滤器链
 */
public class JmsFilterChain implements FilterChain {

    /**
     * 链条上的所有过滤器
     */
    private final Filter[] filters;
    /**
     * servlet
     */
    private final Servlet servlet;
    private int executed;

    public JmsFilterChain(Filter[] filters, Servlet servlet) {
        this.filters = filters;
        this.servlet = servlet;
        executed = 0;
    }

    public Servlet getServlet() {
        return servlet;
    }

    /**
     * 通过此方法依次执行过滤器
     * @param request 请求
     * @param response  响应
     * @throws ServletException ServletException
     * @throws IOException IOException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        if (executed++ < filters.length) {
            filters[executed - 1].doFilter(request, response, this);
        } else {
            servlet.service(request, response);
        }
    }
}
